package com.ygj.easemob.server.example;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.ygj.easemob.server.example.api.ChatGroupAPI;
import com.ygj.easemob.server.example.api.ChatMessageAPI;
import com.ygj.easemob.server.example.api.ChatRoomAPI;
import com.ygj.easemob.server.example.api.FileAPI;
import com.ygj.easemob.server.example.api.IMUserAPI;
import com.ygj.easemob.server.example.api.SendMessageAPI;
import com.ygj.easemob.server.example.comm.ClientContext;
import com.ygj.easemob.server.example.comm.EasemobRestAPIFactory;
import com.ygj.easemob.server.example.comm.body.ChatGroupBody;
import com.ygj.easemob.server.example.comm.body.IMUserBody;
import com.ygj.easemob.server.example.comm.wrapper.BodyWrapper;

public class Main {

	public static void main(String[] args) throws Exception {
		EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();
		
		IMUserAPI user = (IMUserAPI)factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
		ChatMessageAPI chat = (ChatMessageAPI)factory.newInstance(EasemobRestAPIFactory.MESSAGE_CLASS);
		FileAPI file = (FileAPI)factory.newInstance(EasemobRestAPIFactory.FILE_CLASS);
		SendMessageAPI message = (SendMessageAPI)factory.newInstance(EasemobRestAPIFactory.SEND_MESSAGE_CLASS);
		ChatGroupAPI chatgroup = (ChatGroupAPI)factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
		ChatRoomAPI chatroom = (ChatRoomAPI)factory.newInstance(EasemobRestAPIFactory.CHATROOM_CLASS);
		ChatMessageAPI chatMessage = (ChatMessageAPI) factory.newInstance(EasemobRestAPIFactory.MESSAGE_CLASS);

//		BodyWrapper userBody1 = new IMUserBody("3675", "123456", "丁立荣");
//		System.out.println(user.createNewIMUserSingle(userBody1));

//		System.out.println(user.getIMUsersByUserName("677"));
		Class.forName("net.sourceforge.jtds.jdbc.Driver");
		Connection connection = DriverManager.getConnection("jdbc:jtds:sqlserver://120.25.120.99:59999/db_cjy", "cjy_user", "dba@cjy");
		PreparedStatement preparedStatement = null;
		ResultSet resultSet =  null;
		
		preparedStatement = connection.prepareStatement("select e.id, e.name from t_employee as e JOIN t_employee_compounds as ec on e.id = ec.employee_id where e.status=1 and ec.compounds_id = 107");
		resultSet = preparedStatement.executeQuery();
		int i = 0;
		while(resultSet.next()) {
			BodyWrapper userBody = new IMUserBody(resultSet.getString("id"), "123456", resultSet.getString("name"));
			System.out.println(user.createNewIMUserSingle(userBody));
		}
		
		preparedStatement = connection.prepareStatement("select compound.id, compound.name, compound.manager_id, employee.name as employee_name from t_compounds as compound join t_employee as employee on compound.manager_id = employee.id where compound.id=107");
		resultSet = preparedStatement.executeQuery();
		while (resultSet.next()) {
			int id = resultSet.getInt("id");
			String name = resultSet.getString("name");
			String username = resultSet.getString("manager_id");
			String nickname = resultSet.getString("employee_name");
			if(Integer.valueOf(user.getIMUsersByUserName(username).toString().split("Response Body")[0].split(":")[1].trim()) != 200) {
				BodyWrapper userBody = new IMUserBody(username, "123456", nickname);
				System.out.println("添加群主：" + user.createNewIMUserSingle(userBody));
			}
			PreparedStatement preparedStatement2 = connection.prepareStatement("select e.id from t_employee as e JOIN t_employee_compounds as ec on e.id = ec.employee_id where e.status=1 and ec.compounds_id = " + id );
			ResultSet resultSet2 = preparedStatement2.executeQuery();
			List<String> strings = new ArrayList<String>();
			while(resultSet2.next()){
				strings.add(resultSet2.getString("id"));
			}
			String[] strArr = new String[strings.size()];
			String[] objects = strings.toArray(strArr);
			
			BodyWrapper bodyWrapper = new ChatGroupBody(name, name, true, Long.valueOf("2000"), true, username, objects);
			System.out.println("添加群组：" +  chatgroup.createChatGroup(bodyWrapper));
			
			preparedStatement2.close();
			resultSet2.close();
		}
		resultSet.close();
		preparedStatement.close();
		
		connection.close();
		
        /*ResponseWrapper fileResponse = (ResponseWrapper) file.uploadFile(new File("d:/logo.png"));
        String uuid = ((ObjectNode) fileResponse.getResponseBody()).get("entities").get(0).get("uuid").asText();
        String shareSecret = ((ObjectNode) fileResponse.getResponseBody()).get("entities").get(0).get("share-secret").asText();
        InputStream in = (InputStream) ((ResponseWrapper) file.downloadFile(uuid, shareSecret, false)).getResponseBody();
        FileOutputStream fos = new FileOutputStream("d:/logo1.png");
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }
        fos.close();*/

		// Create a IM user
//		BodyWrapper userBody = new IMUserBody("1", "123456", "Kat");
//		System.out.println(user.createNewIMUserSingle(userBody).toString());
        

		// Create some IM users
//		List<IMUserBody> users = new ArrayList<IMUserBody>();
//		users.add(new IMUserBody("User002", "123456", null));
//		users.add(new IMUserBody("User003", "123456", null));
//		BodyWrapper usersBody = new IMUsersBody(users);
//		user.createNewIMUserBatch(usersBody);
		
		// Get a IM user
		/*if(Integer.valueOf(user.getIMUsersByUserName("1").toString().split("Response Body")[0].split(":")[1].trim()) == 200) {
			
		}*/
		
		// Get a fake user
//		System.out.println(user.getIMUsersByUserName("11"));
		
		// Get 12 users
//		user.getIMUsersBatch(null, null);
		
//		BodyWrapper bodyWrapper = new ChatGroupBody("myTest", "myTest", true, Long.valueOf("2000"), true, "User002", new String[]{});
//		chatgroup.createChatGroup(bodyWrapper);
//		System.out.println(chatgroup.getChatGroupDetails(new String[]{"239007517198254512"}).toString());
//		System.out.println(chatgroup.addSingleUserToChatGroup("239007517198254512", "User002").toString());
	
//		Timestamp timestamp = new Timestamp(Long.valueOf("1475993185293"));
//		System.out.println(timestamp.toString());
//		System.out.println(timestamp.valueOf("2014-06-19 15:58:54.226").getTime());
//		System.out.println(chatMessage.exportChatMessages(null, null, "ql=select+*+where+timestamp>1403164734226"));1475890715919 \ 1475893754758
//		List<Map> list = (List<Map>)(JsonUtil.string2Obejct(chatMessage.exportChatMessages(null, null, "select * where timestamp>1475893754758").toString(), Map.class).get("entities"));
//		System.out.println(chatMessage.exportChatMessages(null, null, "select * where timestamp>1475893754758"));
//		System.out.println(chatMessage.exportChatMessages(null, null, "select * where timestamp>1403164734226").toString());
		
	}

	public static String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
        if(str != null) {
            //用默认字符编码解码字符串。与系统相关，中文windows默认为GB2312
            byte[] bs = str.getBytes();
            return new String(bs, newCharset);    //用新的字符编码生成字符串
        }
        return null;
    }
}
